import { config } from '../../config/index';

/**
 * 通用请求函数
 * @param {string} url 请求路径
 * @param {Object} options 请求配置
 * @returns {Promise} 请求结果
 */
export function request(url, options = {}) {
  const { method = 'GET', data, header = {} } = options;
  const fullUrl = url.startsWith('http') ? url : `${config.apiBaseUrl}${url}`;

  return new Promise((resolve, reject) => {
    wx.request({
      url: fullUrl,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        ...header,
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          console.error('请求失败:', res);
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (error) => {
        console.error('网络错误:', error);
        reject(new Error(`网络错误: ${error.errMsg}`));
      },
    });
  });
}

